#include <iostream>
#include <muduo/net/TcpClient.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/EventLoopThread.h>
#include <muduo/net/TcpConnection.h>
#include <muduo/net/TcpServer.h>
#include <muduo/net/Buffer.h>
#include <muduo/base/CountDownLatch.h>
#include <string>
#include <unordered_map>

class DictServer
{
public:
    DictServer(int port):_server(&_eve_loop,
        muduo::net::InetAddress("0.0.0.0",port),
        "DictServer",muduo::net::TcpServer::kReusePort)
    {
        //获取非静态成员函数的地址时，必须显式指定类名
        _server.setConnectionCallback(std::bind(&DictServer::OnConnection,this,std::placeholders::_1));
        _server.setMessageCallback(std::bind(&DictServer::OnMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));
    }
    void start()
    {
        _server.start();
        _eve_loop.loop();
    }
private:
    //设置回调函数
    void OnMessage(const muduo::net::TcpConnectionPtr& conn,muduo::net::Buffer* buffer,muduo::Timestamp timestamp)
    {
        std::unordered_map<std::string,std::string> um = {
            {"handsome","一代"},
            {"apple","苹果"},
            {"tencent","腾讯"}
        };

        std::string msg = buffer->retrieveAllAsString();
        
        std::string res;    
        std::unordered_map<std::string,std::string>::iterator it = um.find(msg);
        if(it == um.end()) res = "查找失败";
        else res = it->second;

        conn->send(res);
    }
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected()) std::cout << "建立连接成功" << std::endl;
        else std::cout << "建立连接失败" << std::endl;
    }
private:
    muduo::net::EventLoop _eve_loop;
    muduo::net::TcpServer _server;
};
int main()
{
    DictServer dict(9090);
    dict.start();
    return 0;
}

